/**
 * Created by yhj on 2017/9/21.
 * 公共
 */
import React, {Component} from 'react';
import {
    Alert,
    Dimensions,
    Linking,
    Platform
} from 'react-native';


export let screenW = Dimensions.get('window').width;
export let screenH = Dimensions.get('window').height;
// iPhoneX
const X_WIDTH = 375;
const X_HEIGHT = 812;

/**
 * 判断是否为iphoneX
 * @returns {boolean}
 */
function isIphoneX() {
    return (
        Platform.OS === 'ios' &&
        ((screenH === X_HEIGHT && screenW === X_WIDTH) ||
            (screenH === X_WIDTH && screenW === X_HEIGHT))
    )
}

/**
 * 根据是否是iPhoneX返回不同的样式
 * @param iphoneXStyle
 * @param iosStyle
 * @param androidStyle
 * @returns {*}
 */

// function ifIphoneX(iphoneXStyle, iosStyle, androidStyle) {
//     if (isIphoneX()) {
//         return iphoneXStyle;
//     } else if (Platform.OS === 'ios') {
//         return iosStyle
//     } else {
//         if (androidStyle) return androidStyle;
//         return iosStyle
//     }
// }




// const BASE_WIN_HEIGHT = 667;
// const BASE_WIN_WIDTH = 375;

const BASE_WIN_HEIGHT = 667;
const BASE_WIN_WIDTH = 375;

function isEmpty(str) {
    return str === null || str === '' || str === undefined;
}

// 根据时间戳格式化时间为**分钟前，**天前这种格式
function getFormattedTime(timestamp) {
    let curTime = Date.parse(new Date()) / 1000;
    let delta = curTime - timestamp;
    const hour = 60 * 60;
    const day = 24 * hour;
    const month = 30 * day;
    const year = 12 * month;
    if (delta < hour) {
        // 显示多少分钟前
        let n = parseInt(delta / 60);
        if (n == 0) {
            return "刚刚";
        }
        return n + '分钟前';
    } else if (delta >= hour && delta < day) {
        return parseInt(delta / hour) + '小时前';
    } else if (delta >= day && delta < month) {
        return parseInt(delta / day) + '天前';
    } else if (delta >= month && delta < year) {
        return parseInt(delta / month) + '个月前';
    }
}

// 身份证号码校验
function  isAvailableIDNumber(id) {
    // 1 "验证通过!", 0 //校验不通过
    var format = /^(([1][1-5])|([2][1-3])|([3][1-7])|([4][1-6])|([5][0-4])|([6][1-5])|([7][1])|([8][1-2]))\d{4}(([1][9]\d{2})|([2]\d{3}))(([0][1-9])|([1][0-2]))(([0][1-9])|([1-2][0-9])|([3][0-1]))\d{3}[0-9xX]$/;
    //号码规则校验
    if(!format.test(id)){
        return {'status':0,'msg':'身份证号码不合规'};
    }
    //区位码校验
    //出生年月日校验   前正则限制起始年份为1900;
    var year = id.substr(6,4),//身份证年
        month = id.substr(10,2),//身份证月
        date = id.substr(12,2),//身份证日
        time = Date.parse(month+'-'+date+'-'+year),//身份证日期时间戳date
        now_time = Date.parse(new Date()),//当前时间戳
        dates = (new Date(year,month,0)).getDate();//身份证当月天数
    if(time>now_time||date>dates){
        return {'status':0,'msg':'出生日期不合规'}
    }
    //校验码判断
    var c = new Array(7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2);   //系数
    var b = new Array('1','0','X','9','8','7','6','5','4','3','2');  //校验码对照表
    var id_array = id.split("");
    var sum = 0;
    for(var k=0;k<17;k++){
        sum+=parseInt(id_array[k])*parseInt(c[k]);
    }
    if(id_array[17].toUpperCase() != b[sum%11].toUpperCase()){
        return {'status':0,'msg':'身份证校验码不合规'}
    }
    return {'status':1,'msg':'校验通过'}
}

// 手机号码校验
function  isPhoneAvailable(phone) {
    var myreg=/^[1][3,4,5,7,8][0-9]{9}$/;
    if (!myreg.test(phone)) {
        return false;
    } else {
        return true;
    }
}

// 格式化url
function format(url, args) {
    /// <summary>
    ///	 格式化字符串"{0} is {1}".format("tom", "cat");
    /// </summary>
    for (var i in args){
        var reg = new RegExp("{(" + i + ")}", "g");
        url = url.replace(reg, args[i]);
    }
    return url;
}

// 根据实际屏幕尺寸转换对应的像素高度
function getHeight(h) {
    if (!this.height) {
        var {height, width} = Dimensions.get('window');
        this.height = height;
        this.width = width;
    }
    return h / 2 * (this.height / BASE_WIN_HEIGHT);
}

// 根据实际屏幕尺寸转换对应的像素宽度
function getWidth(w) {
    if (!this.width) {
        var {height, width} = Dimensions.get('window');
        this.height = height;
        this.width = width;
    }
    return w / 2 * (this.width / BASE_WIN_WIDTH);
}

// 剔除数组第一个元素
function curtail(arr) {
    var m = arr.slice(0);
    m.shift();
    return m;
}

// 剔除数组最后一个元素,返回数组
function DeleteArrLast(arr) {
    return arr.slice(0,-1);
}

// 字符串用逗号分割为数组,且最后一个元素里有@,把最后一个元素用@分割,然后前后拼接
function ModifyArrayContainSymbol(string){
    var arr = string.split(',');
    var noLastArr = this.DeleteArrLast(arr);
    var lastArr = arr[arr.length-1].split('@');
    return noLastArr.concat(lastArr);
}

// 时间戳转时间
function TimestampToTimeSymbol(timestamp,bool,symbol) {
    var Y,M,D,h,m,s;
    var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    Y = date.getFullYear() + symbol;
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + symbol;
    D = date.getDate() <10?'0'+date.getDate()+ ' ':date.getDate() + ' ';

    // D = date.getDate() + ' ';
    h = date.getHours() + symbol;
    m = date.getMinutes()<10? '0'+date.getMinutes() + ':':date.getMinutes() + ':';
    // m = date.getMinutes() + ':';
    // s = date.getSeconds();
    s = date.getSeconds()<10?'0'+date.getSeconds():date.getSeconds();
    if(bool){
        return Y+M+D;
    }else{
        return Y+M+D+h+m+s;
    }
}

function TimestampToTime(timestamp,bool) {
    var Y,M,D,h,m,s;
    var date = new Date(timestamp * 1000);//时间戳为10位需*1000，时间戳为13位的话不需乘1000
    Y = date.getFullYear() + '.';
    M = (date.getMonth()+1 < 10 ? '0'+(date.getMonth()+1) : date.getMonth()+1) + '.';
    D = date.getDate() <10?'0'+date.getDate()+ ' ':date.getDate() + ' ';

    // D = date.getDate() + ' ';
    h = date.getHours() + ':';
    m = date.getMinutes()<10? '0'+date.getMinutes() + ':':date.getMinutes() + ':';
    // m = date.getMinutes() + ':';
    // s = date.getSeconds();
    s = date.getSeconds()<10?'0'+date.getSeconds():date.getSeconds();
    if(bool){
        return Y+M+D;
    }else{
        return Y+M+D+h+m+s;
    }
}

function getDateDiff1(timestamp) {
    // 补全为13位
    var arrTimestamp = (timestamp + '').split('');
    for (var start = 0; start < 13; start++) {
        if (!arrTimestamp[start]) {
            arrTimestamp[start] = '0';
        }
    }
    timestamp = arrTimestamp.join('') * 1;

    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now - timestamp;

    // 如果本地时间反而小于变量时间
    if (diffValue < 0) {
        return '不久';
    }

    // 计算差异时间的量级
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;

    // 数值补0方法
    var zero = function (value) {
        if (value < 10) {
            return '0' + value;
        }
        return value;
    };

    // 使用
    if (monthC > 12) {
        // 超过1年，直接显示年月日
        return (function () {
            var date = new Date(timestamp);
            return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) + '日';
        })();
    } else if (monthC >= 1) {
        return parseInt(monthC) + "月";
    } else if (weekC >= 1) {
        return parseInt(weekC) + "周";
    } else if (dayC >= 1) {
        return parseInt(dayC) + "天";
    } else if (hourC >= 1) {
        return parseInt(hourC) + "小时";
    } else if (minC >= 1) {
        return parseInt(minC) + "分钟";
    }
    return '刚刚';
}


 function  getDateDiff(timestamp) {
    // 补全为13位
    var arrTimestamp = (timestamp + '').split('');
    for (var start = 0; start < 13; start++) {
        if (!arrTimestamp[start]) {
            arrTimestamp[start] = '0';
        }
    }
    timestamp = arrTimestamp.join('') * 1;

    var minute = 1000 * 60;
    var hour = minute * 60;
    var day = hour * 24;
    var halfamonth = day * 15;
    var month = day * 30;
    var now = new Date().getTime();
    var diffValue = now - timestamp;

    // 如果本地时间反而小于变量时间
    if (diffValue < 0) {
        return '不久前';
    }

    // 计算差异时间的量级
    var monthC = diffValue / month;
    var weekC = diffValue / (7 * day);
    var dayC = diffValue / day;
    var hourC = diffValue / hour;
    var minC = diffValue / minute;

    // 数值补0方法
    var zero = function (value) {
        if (value < 10) {
            return '0' + value;
        }
        return value;
    };

    // 使用
    if (monthC > 12) {
        // 超过1年，直接显示年月日
        return (function () {
            var date = new Date(timestamp);
            return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) + '日';
        })();
    } else if (monthC >= 1) {
        return parseInt(monthC) + "月前";
    } else if (weekC >= 1) {
        return parseInt(weekC) + "周前";
    } else if (dayC >= 1) {
        return parseInt(dayC) + "天前";
    } else if (hourC >= 1) {
        return parseInt(hourC) + "小时前";
    } else if (minC >= 1) {
        return parseInt(minC) + "分钟前";
    }
    return '刚刚';
}

// function getDateDiff(timestamp) {
//     // 补全为13位
//     var arrTimestamp = (timestamp + '').split('');
//     for (var start = 0; start < 13; start++) {
//         if (!arrTimestamp[start]) {
//             arrTimestamp[start] = '0';
//         }
//     }
//     timestamp = arrTimestamp.join('') * 1;
//
//     var minute = 1000 * 60;
//     var hour = minute * 60;
//     var day = hour * 24;
//     var halfamonth = day * 15;
//     var month = day * 30;
//     var now = new Date().getTime();
//     var diffValue = now - timestamp;
//
//     // 如果本地时间反而小于变量时间
//     if (diffValue < 0) {
//         return '不久前';
//     }
//
//     // 计算差异时间的量级
//     var monthC = diffValue / month;
//     var weekC = diffValue / (7 * day);
//     var dayC = diffValue / day;
//     var hourC = diffValue / hour;
//     var minC = diffValue / minute;
//
//     // 数值补0方法
//     var zero = function (value) {
//         if (value < 10) {
//             return '0' + value;
//         }
//         return value;
//     };
//
//     // 使用
//     if (monthC > 12) {
//         // 超过1年，直接显示年月日
//         return (function () {
//             var date = new Date(timestamp);
//             return date.getFullYear() + '年' + zero(date.getMonth() + 1) + '月' + zero(date.getDate()) + '日';
//         })();
//     } else if (monthC >= 1) {
//         return parseInt(monthC) + "月前";
//     } else if (weekC >= 1) {
//         return parseInt(weekC) + "周前";
//     } else if (dayC >= 1) {
//         return parseInt(dayC) + "天前";
//     } else if (hourC >= 1) {
//         return parseInt(hourC) + "小时前";
//     } else if (minC >= 1) {
//         return parseInt(minC) + "分钟前";
//     }
//     return '刚刚';
// }

// 生成随机数
function  randomNum(minNum,maxNum){
    switch(arguments.length){
        case 1:
            return parseInt(Math.random()*minNum+1);
            break;
        case 2:
            return parseInt(Math.random()*(maxNum-minNum+1)+minNum);
            break;
        default:
            return 0;
            break;
    }
}

// 生日选择
function  CreateBirthDateData() {
    let date = [];
    for(let i=1970;i<2020;i++){
        let month = [];
        for(let j = 1;j<13;j++){
            let day = [];
            if(j === 2){
                for(let k=1;k<29;k++){
                    day.push(k);
                }
                //Leap day for years that are divisible by 4, such as 2000, 2004
                if(i%4 === 0){
                    day.push(29);
                }
            }
            else if(j in {1:1, 3:1, 5:1, 7:1, 8:1, 10:1, 12:1}){
                for(let k=1;k<32;k++){
                    day.push(k);
                }
            }
            else{
                for(let k=1;k<31;k++){
                    day.push(k);
                }
            }
            let _month = {};
            _month[j] = day;
            month.push(_month);
        }
        let _date = {};
        _date[i] = month;
        date.push(_date);
    }
    return date;
}


// 安装微信
function InstallWechat(){
    var getWeChatUrl = 'itms-apps://itunes.apple.com/cn/app/%E5%BE%AE%E4%BF%A1/id414478124?mt=8';
    Linking.canOpenURL(getWeChatUrl)
        .then((supported)=>{
            if (!supported){
                console.log('Can\'t handle url: ' + url);
                Alert.alert(
                    '提示',
                    'Can\'t handle url: ' + url,
                    [
                        {text: 'OK', onPress:()=>{}}
                    ]
                );
            }else{
                return Linking.openURL(getWeChatUrl);
            }
        })
        .catch((err)=>{
            console.log('An error occurred', err);
            Alert.alert(
                '提示',
                'An error occurred: ' + err,
                [
                    {text: 'OK', onPress:()=>{}}
                ]
            );
        });
}

// 把一个数组重新分组
function groupArray(data, cols) {
    const list = [];
    let current = [];

    // for (t of data) {
    data.forEach(t => {
        current.push(t);
        if (current.length === cols) {
            list.push(current);
            current = [];
        }
    });
    // }    // for (t of data)

    if (current.length) {
        list.push(current);
    }
    return list;
}

// 加载网路图片处理 如果没有图片显示占位图 否则显示网络图片
function isHasImgUrl(imgUrl,defaultImg){
    var img;
    if (imgUrl) {
        img = { uri:imgUrl }
    } else {
        img = defaultImg
    }
    return img;
}

module.exports = {
    isEmpty: isEmpty,
    getFormattedTime: getFormattedTime,
    isAvailableIDNumber:isAvailableIDNumber,
    isPhoneAvailable:isPhoneAvailable,
    format: format,
    getHeight:getHeight,
    getWidth:getWidth,
    // isIphone:isIphoneX,
    isIphoneX:isIphoneX,
    DeleteArrLast:DeleteArrLast,
    ModifyArrayContainSymbol:ModifyArrayContainSymbol,
    TimestampToTime:TimestampToTime,
    randomNum:randomNum,
    CreateBirthDateData:CreateBirthDateData,
    InstallWechat:InstallWechat,
    getDateDiff:getDateDiff,
    getDateDiff1:getDateDiff1,
    TimestampToTimeSymbol:TimestampToTimeSymbol,
    groupArray:groupArray,
    isHasImgUrl:isHasImgUrl,
    // getDateDiff:getDateDiff
}
